package com.example.springboot_system.shiro;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.springboot_system.mapper.RoleMapper;
import com.example.springboot_system.mapper.UserMapper;
import com.example.springboot_system.pojo.Announce;
import com.example.springboot_system.pojo.LoginInfo;
import com.example.springboot_system.pojo.Role;
import com.example.springboot_system.pojo.User;
import com.example.springboot_system.utils.GetIp;
import com.example.springboot_system.utils.IpAddress;
import com.example.springboot_system.utils.ResponseResult;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Date;
import java.util.List;

public class UserRealm extends AuthorizingRealm {

    @Autowired(required = false)
    private UserMapper userMapper;
    @Autowired(required = false)
    private RoleMapper roleMapper;

    // 授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {

//        System.out.println("进入了doGetAuthorizationInfo"+"\n");
        User currentUser = (User) principalCollection.getPrimaryPrincipal();
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("email",currentUser.getEmail());
        User user = userMapper.selectOne(wrapper);

//        System.out.println("currentUser:"+currentUser+"\n");
//        System.out.println("user:"+user+"\n");

        if (user == null) {
            return null;
        }
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        List<Role> listRole = roleMapper.findByUserIdAndRoleStatus(user.getId());
        if(listRole != null){
            for (Role r: listRole) {
//                System.out.println(user.getUsername()+"拥有："+r.getRole()+"  身份");
                info.addRole(r.getRole());
            }
        }
        return info;
    }

    // 认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        System.out.println("进入了doGetAuthenticationInfo"+"\n");
        UsernamePasswordToken userToken = (UsernamePasswordToken) authenticationToken;
        String email = userToken.getUsername();

//        System.out.println("执行了：doGetAuthenticationInfo,邮箱是:"+email);

        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("email",email);
        User user = userMapper.selectOne(wrapper);
//        System.out.println("user:"+user);

        if (user == null) {
            return null;
        }

        String realmName = getName();
//        System.out.println("realmName:"+realmName);

        return new SimpleAuthenticationInfo(user, user.getPlainPassword(), realmName);
    }
}
